import os
import time
import traceback

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from pynput.mouse import Controller, Button


# 小书亭
class XST:
    browser = ""  # 浏览器句柄

    base_url = "https://m.xiaoshuting.org/"

    def __init__(self, is_browser=True):
        if is_browser:
            # 获取网站目录
            root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd())))
            executable_path = root_path + "\chromedriver\\125\\chromedriver.exe"

            chrome_options = Options()
            chrome_options.add_argument("--disable-infobars")
            chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
            chrome_options.add_experimental_option('useAutomationExtension', False)
            self.browser = webdriver.Chrome(service=ChromeService(executable_path=executable_path), options=chrome_options)

    def check_ture_people(self, number=10):
        try:
            # 真人验证
            is_check = self.browser.find_element(By.ID, "challenge-running").text
            if '是真人' in is_check:
                # 查找真人选项按钮
                print("睡眠开始")
                time.sleep(20)
                print("睡眠结束，开始点击")

                mouse = Controller()
                mouse.position = (100, 470)
                time.sleep(5)
                print("鼠标移动到验证码, 并且点击")
                for i in range(3):
                    mouse.click(Button.left, 1)
                    time.sleep(2)

            else:
                return True

        except Exception:
            print("验证破解", traceback.print_exc())

        if number <= 0:
            print("10完成，但任然还有验证")
            return False
        print("次数", number)

        number = number - 1
        self.check_ture_people(number)

    def run_task(self):
        self.browser.get(self.base_url)
        # 查找输入框， 等待元素可见
        wait = WebDriverWait(self.browser, 10)  # 10秒的超时时间
        element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "searchForm_input")))
        element.send_keys("这游戏也太真实了")
        # 点击搜索按钮
        self.browser.find_element(By.CLASS_NAME, "serach_span").click()

        # 查询是否需要验证
        self.check_ture_people()

        # # 查找目录
        # soup = BeautifulSoup(self.browser.page_source, 'lxml')
        # time.sleep(10)
        # print(soup)
        # # 查找输入框并输入文字触发
        # soup.find(".")

        # # 获取目录
        # menu = soup.select(".info-chapters")[-1].select("a")
        # for index, item in enumerate(menu):
        #     if start_chapter <= index + 1 <= end_chapter:
        #         yield item

        self.browser.close()

    def test(self):
        # xst = XST(is_browser=True)
        # xst.run_task()

        root_path = os.getcwd()
        executable_path = root_path + "\\chromedriver.exe"

        chrome_options = Options()
        chrome_options.add_argument("--headless")  # 无头模式运行
        chrome_options.add_argument("--no-sandbox")  # 禁用沙盒模式
        chrome_options.add_argument("--disable-dev-shm-usage")  # 禁用 /dev/shm 使用
        chrome_options.add_argument("--disable-gpu")  # 禁用 GPU 加速

        browser = webdriver.Chrome(service=ChromeService(executable_path=executable_path), options=chrome_options)

        browser.execute_cdp_cmd('Network.setUserAgentOverride', {
            "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36"
        })

        base_url = "https://m.xiaoshuting.org/book/433/"
        browser.get(base_url)


        print(browser.page_source)


        # # 查找输入框， 等待元素可见
        # wait = WebDriverWait(browser, 60)  # 10秒的超时时间
        # element = wait.until(EC.presence_of_element_located((By.CLASS_NAME, "searchForm_input")))
        # element.send_keys("这游戏也太真实了")
        # # 点击搜索按钮
        # browser.find_element(By.CLASS_NAME, "serach_span").click()

        # # 等待验证字符串出现
        # element = wait.until(EC.presence_of_element_located((By.ID, "challenge-running")))
        # is_check = element.text
        # if '是真人' in is_check:
        #
        #     time.sleep(10)
        #
        #     # 创建鼠标控制器
        #     mouse = Controller()
        #     mouse.position = (105, 420)
        #
        #     print("移动鼠标到选择按钮")
        #
        #     time.sleep(2)
        #
        #     print("鼠标移动到验证码, 并且点击")
        #     for i in range(1):
        #         mouse.click(Button.left, 1)
        #         time.sleep(2)

        time.sleep(60)

        browser.close()


if __name__ == '__main__':
    pass